var _expire_time=30*60*1000
    ,_interval_handler=-1
    ,_lock_pwd="123456"
    ,dynamicAddTab
    ,dynamicCloseTab
    ,layer
    ,element
    ,navbar
    ,tab
    ,$;
layui.config({
    base: 'assets/js/'
}).use(['layer','element', 'navbar', 'tab'], function(){
    layer = parent.layer === undefined ? layui.layer : top.layer,
    element = layui.element,
    navbar = layui.navbar(),
    $ = layui.jquery,
    tab = layui.tab({
        elem: '.admin-nav-card'
    });
    if(devices=="app"){
       renderMenus(navs);
    }
    //判断是否登录
    var memberObjStr = sessionStorage.getItem("pt_memberInfo");
    if (memberObjStr) {
        //刷新最后使用时间
        sessionStorage.setItem("pt_lastVisitTime", new Date().getTime());
       _interval_handler=setInterval(checkExpired, 10*1000);
    }
    //判断是否锁屏
    var lockedStr = window.sessionStorage.getItem("pt_locked");
    if (lockedStr == "true") {
        lockPage();
    }
    //页面尺寸适应
    $(window).on('resize', function() {
        devices = $('#admin-body').width() <= 768 ? "app" : "";
        var $render = devices == "app" ? renderMenus(navs) : "";
        var $content = $('.admin-nav-card .layui-tab-content');
        $content.height($(this).height() - 130);
        $content.find('iframe').each(function() {
            $(this).height($content.height());
        });
    }).resize();
    //动态添加Tab选项卡
    dynamicAddTab = function (tabTitle, tabHref, tabIcon, targetHref){
        tab.tabAdd({
            title: tabTitle,
            href: tabHref,
            icon: tabIcon
        });
        if(targetHref!="" && targetHref!=null){
            var $content = $('.layui-body .layui-tab-content');
            $content.find('iframe').each(function() {
                if($(this).attr("src")==tabHref){
                    $(this).context.contentWindow.location.href=targetHref;
                }
            });
        }
        let topMenu = "";//顶部菜单
        let leftMenus = [];//左侧菜单
        let isExist = false;//是否存在
        $.each(navs, function(index, menu){
            if(isExist) return false;
            topMenu = menu.title;
            if(menu.title == tabTitle){
                return false;
            }
            if(menu.children != undefined){
                eachsMenu(menu.children);
            }
        });
        // 遍历左侧菜单查找目标菜单
        function eachsMenu(menus){
            $.each(menus, function(index, menu){
                if(isExist) return false;
                leftMenus.push(menu.title);
                if(menu.title == tabTitle){
                    isExist = true;
                    return false;
                }else if(menu.children!=undefined){
                    eachsMenu(menu.children);
                }else{
                    leftMenus.pop(menu.title);
                }
            });
        }
        // 如果找到菜单，渲染上级菜单状态
        if(isExist){
            $('.menu-list .layui-nav-item').each(function(){
                if($(this).find("a:first-child").attr('data-title') == topMenu){
                    $(this).click().addClass('layui-this').siblings().removeClass('layui-this');
                }
            });
            let lastIndex = leftMenus.length - 1;
            if(lastIndex > -1){
                $.each(leftMenus, function(index, title){
                    $('.layui-side').find('cite').each(function(){
                        if($(this).text() == title){
                            if(lastIndex == index){
                                $(this).parent().parent().addClass('layui-this').siblings().removeClass('layui-this');;
                            }else{
                                $(this).parent().parent().addClass('layui-nav-itemed').siblings().removeClass('layui-nav-itemed');
                            }
                        }
                    })
                });
            }
        }
        topMenu = "";
        leftMenus = [];
    }
    //动态关闭Tab选项卡
    dynamicCloseTab = function (tabTitle){
        let closeTabObj = $('ul.layui-tab-title cite:contains("' + tabTitle+ '")');
        if(closeTabObj.length > 0){
            element.tabDelete('admin-tab', closeTabObj.parent('li').attr('lay-id')).render();
        }
    }
    //下拉标签处理
    $('#lay_tabs .layui-nav .layui-nav-item').on('click', function(){
        $(this).find('span.layui-nav-more').first().toggleClass('layui-nav-mored');
        $(this).find('dl.layui-nav-child').first().toggleClass('layui-show');
    })
    $('#closeThisTabs').on('click',function(){
        element.tabDelete('admin-tab', $('ul.layui-tab-title>li.layui-this').attr('lay-id')).render();
        rollPage("auto", $('ul.layui-tab-title>li.layui-this').index());
    })
    $('#closeOtherTabs').on('click',function(){
        $('ul.layui-tab-title>li').not(":first,.layui-this").each(function(index){
            element.tabDelete('admin-tab', $(this).attr('lay-id')).render();
        })
        rollPage("auto", $('ul.layui-tab-title>li.layui-this').index());
    })
    $('#closeAllTabs').on('click',function(){
        $('ul.layui-tab-title>li').not(":first").each(function(index){
            element.tabDelete('admin-tab', $(this).attr('lay-id')).render();
        })
        rollPage("auto", $('ul.layui-tab-title>li.layui-this').index());
    })
    $('#leftPage').on('click', function(){
        rollPage("left");
    })
    $('#rightPage').on('click', function(){
        rollPage("right");
    })
    //使用引导
    $("#tipsSystem").on("click",function(){
        mydriver.start();
    })
    //系统锁屏
    $("#lockSystem").on("click",function(){
        window.sessionStorage.setItem("pt_locked", true);
        lockPage();
    })
    $("body").on("click","#unlock",function(){
        if($(this).siblings(".admin-header-lock-input").val() == ''){
            layer.msg("请输入解锁密码！");
            $(this).siblings(".admin-header-lock-input").focus();
        }else{
            if($(this).siblings(".admin-header-lock-input").val() == _lock_pwd){
                window.sessionStorage.setItem("pt_locked", false);
                $(this).siblings(".admin-header-lock-input").val('');
                layer.closeAll("page");
            }else{
                layer.msg("密码错误，请重新输入！");
                $(this).siblings(".admin-header-lock-input").val('').focus();
            }
        }
    });
    //用户消息
    $("#msgSystem").on("click",function(){
        tab.tabAdd({
            title: '用户消息中心',
            href: 'message/receive/manage',
            icon: 'fa fa-envelope-open'
        });
    })
    //用户资料
    $('#userBase').on('click',function(){
        tab.tabAdd({
            title: '基本资料',
            href: 'admin/userbase/edit',
            icon: '&#xe66f;'
        });
    });
    //密码修改
    $('#editPwd').on('click',function(){
        tab.tabAdd({
            title: '修改密码',
            href: 'admin/users/editpwd',
            icon: '&#xe68e;'
        });
    });
    //站点切换
    $('.js_open').on('click', function(){
        layer.open({
           type: 2,
           title:'平台站点切换',
           area: ['700px', '450px'],
           anim: 2,
           maxmin: true,
           closeBtn: 1,
           shadeClose: true,
           shade: 0.6,
           content: 'website'
         });
    })
    //侧边栏伸缩
    $('.admin-side-toggle').on('click', function() {
        var sideWidth = $('#admin-side').width();
        if($('#admin-navbar-side:has(ul)').length!=0){
            if(sideWidth === 200) {
                $('#admin-body').animate({left: '0px'});
                $('#admin-side').animate({width: '0px'});
                $('#admin-footer').animate({left: '0px'});
            } else {
                $('#admin-body').animate({left: '200px'});
                $('#admin-side').animate({width: '200px'});
                $('#admin-footer').animate({left: '200px'});
            }
        }
    });
    //全屏显示
    $('.admin-side-full').on('click', function() {
        var docElm = document.documentElement;
        //W3C  
        if(docElm.requestFullscreen) {
            docElm.requestFullscreen();
        }
        //FireFox  
        else if(docElm.mozRequestFullScreen) {
            docElm.mozRequestFullScreen();
        }
        //Chrome等  
        else if(docElm.webkitRequestFullScreen) {
            docElm.webkitRequestFullScreen();
        }
        //IE11
        else if(elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
        }
        layer.msg('按Esc即可退出全屏');
    });

    //移动端简单适配
    var treeMobile = $('.site-tree-mobile'),
        shadeMobile = $('.site-mobile-shade');
    treeMobile.on('click', function() {
        $('body').addClass('site-mobile');
        if($('#admin-side').width()===0){
            $('#admin-body').animate({left: '200px'});
            $('#admin-side').animate({width: '200px'});
            $('#admin-footer').animate({left: '200px'});
        }
    });
    shadeMobile.on('click', function() {
        $('body').removeClass('site-mobile');
        $('#admin-body').animate({left: '0px'});
        $('#admin-side').animate({width: '0px'});
        $('#admin-footer').animate({left: '0px'});
    });
});

$(function(){
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
    
    //顶部菜单动态展示
    var hw, hlw, hrw, hc, pm,sm,ml,limitCount,menuCount,limitWidth,limitTranslateX,translateX;
    resizeTopMenu();
    window.onresize = resizeTopMenu;
    function resizeTopMenu(){
        hw = $(window).width();
        hlw = $('.layui-header .layui-layout-left').width();
        hrw = $('.layui-header .layui-layout-right').width();
        
        hc = $('.layui-header .layui-layout-center');
        pm = $('.layui-layout-center .prefix-menu');
        sm = $('.layui-layout-center .suffix-menu');
        ml = $('.layui-layout-center .menu-list');
        
        sm.hide();
        pm.hide();
        menuCount = $('.layui-layout-center .menu-list .layui-nav-item').length;
        limitCount = Math.round((hw - hlw - hrw) * 0.65 / 104);
        limitWidth = limitCount * 104;
        hc.width(limitWidth);
        
        limitTranslateX = 104 * (menuCount - limitCount);
        translateX = 0;
        ml.css({'transform':'translateX('+translateX+'px)','transition': 'all 1s ease;'});
        if(menuCount > limitCount) {
            sm.show();
        }
    }
    sm.on('click', function(){
        translateX = translateX - 104;
        if(Math.abs(translateX) <= limitTranslateX){
            ml.css({'transform':'translateX('+translateX+'px)','transition': 'all 1s ease;'});
        }
        if(Math.abs(translateX) == limitTranslateX){
            sm.hide();
        }
        if(translateX < 0){
            pm.show();
        }
    });
    pm.on('click', function(){
        translateX = translateX + 104;
        if(translateX <= 0){
            ml.css({'transform':'translateX('+translateX+'px)','transition': 'all 1s ease;'});
        }
        if(Math.abs(translateX) < limitTranslateX){
            sm.show();
        }
        if(translateX == 0){
            pm.hide();
        }
    });
    ml.on('click', '.layui-nav-item', function(){
        title = $(this).find(":first").attr("data-title");
        renderMenus();
    });
})

//检查过期
function checkExpired() {
    var storeLastTime=sessionStorage.getItem("pt_lastVisitTime")?sessionStorage.getItem("pt_lastVisitTime"):-1;
    if (storeLastTime==-1) cleareInterval(_interval_handler);
    else {
      if ((new Date()).getTime()-storeLastTime> _expire_time) {
         /** alert("由于您长时间未进行操作，系统将为您自动退出登录",{time:5000});
          *sessionStorage.clear();
          *clearInterval(_interval_handler);
          *document.location.href="logout";
          */
      }
    }
}
//系统锁屏
function lockPage(){
    layer.open({
        title : false,
        type : 1,
        content : '<div class="admin-header-lock" id="lock-box">'+
                        '<div class="admin-header-lock-img"><img src="assets/images/head.png" class="userAvatar"/></div>'+
                        '<div class="admin-header-lock-name" id="lockUserName">认真你就输了</div>'+
                        '<div class="input_btn">'+
                            '<input type="password" class="admin-header-lock-input layui-input" autocomplete="off" placeholder="请输入密码解锁.." id="lockPwd" />'+
                            '<button class="admin-header-lock-btn layui-btn" id="unlock">解锁</button>'+
                        '</div>'+
                        '<div class="admin-header-lock-tip">请输入123456进行解锁！</div>'+
                    '</div>',
        closeBtn : 0,
        shade : 0.9,
        success : function(){
            $(".admin-header-lock-input").focus();
        }
    })
}
//动态添加Tab选项卡
function dynamicAddTab(tabTitle, tabHref, tabIcon, targetHref){
    dynamicAddTab(tabTitle, tabHref, tabIcon, targetHref);
}
//动态关闭Tab选项卡
function dynamicCloseTab(tabTitle){
    dynamicCloseTab(tabTitle);
}
//渲染菜单
function renderMenus(menus){
    if(title != ""){
        $.each(navs, function(index, item){
            if(item.title == title){
                menus = item.children;
                return ;
            }
        });
        if($('#admin-side').width()===0){
            $('#admin-body').animate({left: '200px'});
            $('#admin-side').animate({width: '200px'});
            $('#admin-footer').animate({left: '200px'});
        }
    }
    navbar.set({
        spreadOne: true,
        elem: '#admin-navbar-side',
        cached: true,
        data: menus
    });
    //渲染navbar
    navbar.render();
    //监听点击事件
    navbar.on('click(side)', function(data) {
        $(data.elem.context).siblings().removeClass("layui-nav-itemed");
        if(data.field.href !== undefined){
            tab.tabAdd(data.field); 
            if(devices=="app"){
                $('body').removeClass('site-mobile');
                $('#admin-body').css('left', '0px');
            }
        }
    });
    //点击tab标签，左侧菜单联动并选中,删除其中某个tab后，data.index与实际的index不符
    element.on('tab(admin-tab)', function(data){
        $("iframe[data-id='"+$(this).children("[data-id]").attr("data-id")+"']").each(function(){
            $('.layui-nav').children().removeClass("layui-this");
            $("a[data-url='"+$(this).attr("src")+"']").each(function(){
                $(this).parents('li').siblings().removeClass("layui-nav-itemed");
                $(this).parent().addClass("layui-this").siblings().removeClass("layui-this");
            })
        });
        rollPage("auto", $(this).index());
    });
};
//标签滚动
function rollPage(e, i){
    var lf = 40;//左处理偏移
    var rf = 16;//右偏移处理
    var offsight = 136;//定位偏移
    var t = $('#lay_tabsheader')
    ,n = t.children("li")
    ,l = (t.prop("scrollWidth"), t.outerWidth())
    ,s = parseFloat(t.css('left'));
    l = l - Math.abs(s);
    if("left" === e){
        if(!s && s < 0){
            return;
        }
        var r = -s - l;
        n.each(function(e,i){
            var n = $(i)
            ,l = n.position().left;
            if(l >= r){
                l = l - lf;
                return t.css("left", -l),!1;
            }
        })
    }else if("right" === e){
        n.each(function(e,i){
            var n = $(i)
            ,r = n.position().left;
            if(r + n.outerWidth() >= l - s){
                r = r -lf;
                return t.css("left", -r),!1;
            }
        })
    }else{
        var e, r = n.eq(i);
        if(r[0]){
            if(e = r.position().left, e < -s){
                if(i == 0){
                    return t.css("left", 0);
                }
                e = e - offsight;
                return t.css("left", -e);
            }
            if(e + r.outerWidth()>= l - s ){
                var o = e + r.outerWidth() - (l - s) + offsight;
                n.each(function(e, i){
                    var n = $(i)
                    , l = n.position().left;
                    if(l + s > 0 && l - s > o){
                        l = l + rf;
                        return t.css("left", -l),!1;
                    }
                })
            }
        }
    }
}
